package com.jiuyue.demo.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.jiuyue.demo.Mapper.ExternalContactFollowMapper;
import com.jiuyue.demo.Mapper.ExternalContactFollowTagMapper;
import com.jiuyue.demo.Mapper.ExternalContactMapper;
import com.jiuyue.demo.Mapper.LogUserOperationMapper;
import com.jiuyue.demo.Mapper.LogUserOperationReposity;
import com.jiuyue.demo.Mapper.UserRepository;
import com.jiuyue.demo.entity.ExternalContact;
import com.jiuyue.demo.entity.ExternalContactFollow;
import com.jiuyue.demo.entity.ExternalContactFollowTag;
import com.jiuyue.demo.entity.ExternalUser;
import com.jiuyue.demo.entity.LogUserOperation;
import com.jiuyue.demo.entity.LogUserOperationQuery;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DBObject;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;

import cn.hutool.core.date.DateUtil;

@Service
public class UserServiceImpl implements UserService {
	
	
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private ExternalContactMapper externalContactMapper;
	@Autowired
	private ExternalContactFollowMapper externalContactFollowMapper;
	@Autowired
	private ExternalContactFollowTagMapper externalContactFollowTagMapper;
	@Autowired
	private LogUserOperationMapper logUserOperationMapper;
	@Autowired
	private LogUserOperationReposity logUserOperationReposity;
	@Autowired
    private MongoTemplate mongoTemplate;

	/**
	 * 保存本地的所有用户
	 */
	@Override
	public String saveAllUser() {
		// TODO 自动生成的方法存根
		List<ExternalContact> list = externalContactMapper.selectList(null);
		if(list.size()!=0) {
			for (ExternalContact ex :list ) {
				ExternalUser exUser = new ExternalUser();
				exUser.setExternalContact(ex);
				//获取follow
				QueryWrapper<ExternalContactFollow> followQuery = new QueryWrapper<ExternalContactFollow>();
				followQuery.eq("external_userid",ex.getExternalUserid());
				List<ExternalContactFollow> exFollow =externalContactFollowMapper.selectList(followQuery);
				exUser.setExternalContactFollowList(exFollow);
				//获取tags
				QueryWrapper<ExternalContactFollowTag> tagQuery = new QueryWrapper<ExternalContactFollowTag>();
				tagQuery.eq("external_id", ex.getExternalUserid());
				List<ExternalContactFollowTag> tagList =externalContactFollowTagMapper.selectList(tagQuery);
				exUser.setExternalContactFollowTagsList(tagList);
				Gson gson = new Gson();
				//存储到es中
				//System.out.println("======="+gson.toJson(exUser));
				userRepository.save(exUser);	
			}
		}
		return "保存数据成功";
	}

	@Override
	public  List<ExternalUser> getAll() {
		// TODO 自动生成的方法存根
	    List<ExternalUser> list =	userRepository.findAll();
		return list;
	}

	@Override
	public ExternalUser getUserById( String  id) {
		// TODO 自动生成的方法存根
		ExternalUser externalUser =mongoTemplate.findById(id, ExternalUser.class);
		return externalUser;
	}

	/**
	 * 用户名准确查询
	 */
	@Override
	public List<ExternalUser> getUserByName(String userName) {
		// TODO 业务逻辑
		  Query query = new Query(Criteria .where("username").is(userName));	
		    // .and("gender").is(gender)
            // .and("age").gt(age);
	        List<ExternalUser> externalUsers = mongoTemplate.find(query, ExternalUser.class);
	        return externalUsers;
	}

	/**
	 * 用户名模糊查询
	 * 
	 */
	@Override
	public List<ExternalUser> getUserLikeName(String userName) {
		// TODO 业务逻辑
		String regex = String.format("%s%s%s", "^.*", userName, ".*$");
		System.out.println("查询规则为"+regex);
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Query query = new Query(Criteria.where("externalContact.name").regex(pattern));
        List<ExternalUser> externalUsers = mongoTemplate.find(query, ExternalUser.class);
        return externalUsers;
	}

	/**
	 * 分页查询用户
	 * 
	 */
	@Override
	public List<ExternalUser> getUserBypage(int pageNum, int pageSize) {
		// TODO 业务逻辑
		Query query = new Query();
		int totalCount = (int) mongoTemplate.count(query, ExternalUser.class);
        List<ExternalUser> externalUsers = mongoTemplate.find(query.skip(pageNum).limit(pageSize), ExternalUser.class);
        return externalUsers;
	}

	/**
	 * 修改用户
	 * 
	 */
	@Override
	public String updateUser(ExternalUser externalUser) {
		// TODO 自动生成的方法存根
		 try {
	            Query query = new Query(Criteria.where("_id").is(externalUser.getExternalContact().getId()));
	            Update update = new Update();
	            update.set("externalContact.status", 1);	          
	            UpdateResult result = mongoTemplate.upsert(query, update, ExternalUser.class);
	            long count = result.getModifiedCount();
	            if (count > 0) {
	                return"更新成功";
	            }	     
	        } catch (Exception e) {
	            e.printStackTrace();
	            return"更新失败";
	        }
		 return"更新失败";
	}

	/**
	 * 
	 * 根据id删除用户
	 */
	@Override
	public String deleteUserById(String id) {
		// TODO 业务逻辑
            Query query = new Query(Criteria.where("_id").is(id));
            DeleteResult result = mongoTemplate.remove(query, ExternalUser.class);
            long count = result.getDeletedCount();
            if(count>0) {
            	return "删除成功";
            }
            return "删除失败";           
	}

	@Override
	public String saveLogUser() {
		// TODO 自动生成的方法存根
		LogUserOperationQuery query = new LogUserOperationQuery();
		List<String> url = new ArrayList<>();
		url.add("https://xiktech.com/v1/recordBTurnTableClickNums1");
		url.add("https://xiktech.com/v1/recordHongClickNums");
		url.add("https://xiktech.com/v1/recordDanClickNums");
		url.add("https://xiktech.com/v1/recordXianClickNums");
		url.add("https://xiktech.com/v1/recordTuClickNums");
		url.add("https://xiktech.com/v1/recordFruitClickNums");
		url.add("https://xiktech.com/v1/recordDacheShare");
		url.add("https://xiktech.com/v1/recordDache1Share");
		url.add("https://xiktech.com/v1/recordDache2Share");
		url.add("https://xiktech.com/v1/recordLemonClickNums");
		for (String logUrl : url) {
			query.createCriteria().andUrlEqualTo(logUrl);
			List<LogUserOperation> list =logUserOperationMapper.selectByExample(query);
			if(list.size()!=0) {
				for (LogUserOperation logUserOperation : list) {
					System.out.println("----------------");
					logUserOperationReposity.save(logUserOperation);
				}
			}
			
		}
		
		return "存储日志数据成功";
	}

	
	
	
	@Override
	public int getOpenCount() {
		 Date beginOfDay = DateUtil.beginOfDay(DateUtil.yesterday());
	        //一天的结束，结果：2017-03-01 23:59:59
	        Date endOfDay = DateUtil.endOfDay(DateUtil.yesterday());
	        System.out.println("开始查询mongodb中的数据");
	        DBObject dbObject=  new BasicDBObject();
	        //方法2
	        dbObject.put("createTime", BasicDBObjectBuilder.start("$gte",
	                dateToISODate(beginOfDay)).add("$lt",
	                dateToISODate(endOfDay)).get());
	        dbObject.put("url","https://xiktech.com/v1/recordBTurnTableClickNums1");
	        Query query = new BasicQuery(dbObject.toString());
	        System.out.println("查询条件"+query.toString());
	        List<LogUserOperation> list = mongoTemplate.find(query, LogUserOperation.class);
	        System.out.println("查询结果"+list);
	        return list.size();
	}
	
	
	
	  public static Date dateToISODate(Date dateStr) {
	        Date parse = null;
	        try {
	            // 解析字符串时间
	            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
	            parse = format.parse(format.format(dateStr));
	            System.out.println(parse);
	        } catch (ParseException e) {
	            e.printStackTrace();
	        }
	        return parse;
	    }
	

}
